package com.mctuoluo.mappay;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mctuoluo.mappay.sql.sql;
import com.mctuoluo.mappay.sql.update;
import com.mctuoluo.mappay.vv.loadVV;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import javax.imageio.ImageIO;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.Logger;

public final class MapPay extends JavaPlugin implements Listener {

    Boolean DisplayImageOnWinnerMap = true;
    boolean isvv = true;
    static MapPay ins ;
    java.util.Map<String,Integer> m = new HashMap();
    java.util.Map<Player, ItemStack> item = new HashMap();
    ItemStack map;
    @Override
    public void onEnable() {

        ins = this;

        // Plugin startup logic
        Logger logger = Bukkit.getLogger();
        Bukkit.getPluginManager().registerEvents(this,this);
        Bukkit.getPluginCommand("cz").setExecutor(new Command());
//        update up = null;

//        try {
//            up = new update();
//            up.sql();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }


    }

    public void openMap(Player p,int s,int ss) throws IOException {
        URL l = getImageURL(p,s,ss) ;
        if (isvv == true){

            return;
        }
        addItem(p.getPlayer(),map);

    }
    @EventHandler
    public void chat(AsyncPlayerChatEvent e) throws MalformedURLException {
        //

        if (e.getMessage().equals("qx")){
            if (isStart(e.getPlayer().getName()) == true){
                delStart(e.getPlayer().getName());
                e.setCancelled(true);
                return;
            }
        }
        if (e.getMessage().equals("cx")){
            sql sqls= new sql();
            sqls.sendOrder(e.getPlayer().getName());
            e.setCancelled(true);
        }
    }
    @EventHandler
    public void join(PlayerJoinEvent e){
        update.addCard(e.getPlayer(),0);
    }

    public URL getImageURL(Player p ,int s,int ss){
        URL ssss = null;
        try {

            String u = "http://api2.yy2169.com:52888/creat_order/?id=18179&token=mDQMUDposVVkkCeyol9strH4VnkQe1Ko&price="+String.valueOf(s)+"&pay_id="+p.getName()+"&type="+ss+"&page=4&param="+p.getName()+"_"+System.currentTimeMillis();

            URL url = new URL(u);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = in.readLine();
            //Bukkit.getConsoleSender().sendMessage(line);
            in.close();

            String finalLine = line;

            JsonObject jsonObject = (JsonObject) new JsonParser().parse(finalLine).getAsJsonObject();

            //System.out.println(jsonObject.get("qrcode").getAsString());
            String iurl = jsonObject.get("qrcode").getAsString();
            start(p,jsonObject.get("money").getAsString(),jsonObject.get("order_id").getAsString(),jsonObject.get("endTime").getAsString(),jsonObject.get("type").getAsString(),jsonObject.get("qrcode").getAsString());
           // ssss = new URL(jsonObject.get("qrcode").getAsString());

            ssss = new URL(iurl);

            if (isvv == true){

            }else {
                //预加载二维码
                MapView view = Bukkit.createMap((World) Bukkit.getWorlds().get(0));
                for (MapRenderer renderer : view.getRenderers()) {
                    view.removeRenderer(renderer);
                }
                try {
                    view.addRenderer(new Map(ImageIO.read(new URL(iurl)).getScaledInstance(128, 128, 1), 1, 100));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                map = new ItemStack(Material.MAP, 1, view.getId());
            }

        }
        catch (MalformedURLException e) {
            System.out.println("Malformed URL: " + e.getMessage());
        }
        catch (IOException e2) {
            System.out.println("I/O Error: " + e2.getMessage());
            String u = "http://api2.yy2169.com:52888/creat_order/?id=18179&token=mDQMUDposVVkkCeyol9strH4VnkQe1Ko&price="+String.valueOf(s)+"&pay_id="+p.getName()+"&type="+ss+"&page=4&param="+p.getName()+"_"+System.currentTimeMillis();
            System.out.println("URL: " + u);
        }
        return ssss;
    }

    @EventHandler
    public void quit(PlayerQuitEvent e){
        if (m.get(e.getPlayer().getName()) != null){
            delStart(e.getPlayer().getName());
        }
    }
    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }
    public static MapPay getMapPay(){
        return ins;
    }
    public void start(Player player,String s1,String s2,String s3,String s4,String url){
        sql sqls = new sql();
        sqls.sendOrder(player.getName());
        if (isvv == true){
            loadVV.openMaps(url,100,30,128,128,128,128,player,"§b§l请使用 "+ getType(s4) +" 付款 "+ s1 +" RMB!\n    §c§l请在§f " + getTime(s3)+" §c§l前进行付款，充值完成或取消充值按esc！");
        }

        //player.getLocation().setYaw();
        new BukkitRunnable() {
            boolean id = true;
            @Override
            public void run() {
                if (id == true){
                    addStart(player.getName(),getTaskId());
                    id = false;
                }
                long lt = new Long(s3 );
                lt = lt * 1000;
                if (System.currentTimeMillis() > lt){
                    delItem(player);
                    m.remove(player.getName());
                    player.sendMessage("§c充值失败 请勿付款！");
                    cancel();
                }
                if (sqls.sendOrders(player.getName())){
                    delStart(player.getName());
                    player.sendMessage("§b充值成功到账！");
                    TitleAPI.sendTitle(player,0,120,80,"§a本次充值 "+Float.parseFloat(s1) * 100+" 点券!","§e§l充值成功");
                    cancel();
                }
                //Location loc = player.getLocation();
                //loc.setPitch(90);
                //player.teleport(loc);
                if (isvv== true){

                }else {
                    player.sendMessage("");
                    player.sendMessage("§e============================================================");
                    player.sendMessage("§b§l充值系统 §f>> §e请支付 §f"+s1+"RMB§e 不然订单系统中会查询不到订单！");
                    player.sendMessage("§b§l充值系统 §f>> §e请使用 §f"+getType(s4)+"支付§e 不然订单系统中会查询不到订单");
                    player.sendMessage("§b§l充值系统 §f>> §e若不想充值了，只需在聊天框输入 §cqx §e即可！");
                    player.sendMessage("§b§l充值系统 §f>> §e自动充值没有到账可输入 §ccz §e进行查询订单！");
                    player.sendMessage("§b§l充值系统 §f>> §c付款时间超过 §f" + getTime(s3)+" §c请勿在进行付款！");
                    player.sendMessage("§b§l充值系统 §f>> §c查询订单也未找到充值订单时请联系客服进行补偿！");
                    player.sendMessage("§b§l充值系统 §f>> §c在输入 qx和cx 的时候无需斜杠(/)！");
                    player.sendMessage("§e============================================================");
                }
            }
        }.runTaskTimer(this,5L,0);
    }
    public static String getTime(String e){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        long lt = new Long(e);
        lt = lt *1000;
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    public static String getType(String s4){
        int s = Integer.parseInt(s4);
        switch (s){
            case 1:
                s4 = "支付宝";
            break;
            case 2:
                s4 = "QQ";
            break;
            case 3:
                s4 = "微信";
            break;

        }
        return s4;
    }


    public boolean isStart(String name){
        if (m.get(name) != null){
            return true;
        }
        return false;
    }
    public void addStart(String name ,int i){
        m.put(name,i);
    }
    public void delStart(String name ){
        Bukkit.getScheduler().cancelTask(m.get(name));
        delItem(Bukkit.getPlayer(name));
        m.remove(name);
    }
    @EventHandler
    public void moveinv(PlayerItemHeldEvent event){
        if (isStart(event.getPlayer().getName())){
            event.setCancelled(true);
        }
    }
    public void addItem(Player player,ItemStack itemStack){
        item.put(player,player.getItemInHand());
        player.getInventory().setItem(player.getInventory().getHeldItemSlot(),itemStack);
    }
    public void delItem(Player player){
        player.getInventory().setItem(player.getInventory().getHeldItemSlot(),item.get(player));
        item.remove(player);
    }
    @EventHandler
    public void move(PlayerMoveEvent e){
        if (isStart(e.getPlayer().getName())){
            Location loc = e.getTo();
            if (loc.getPitch() != 90){
                //e.getPlayer().teleport(loc);
            }
            //
        }
    }

}
